package com.wb.spring.boot.autoconfigure.load;

import com.wb.spring.boot.autoconfigure.model.ServerNode;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 加权随机
 */
public class WeightRandomLoad implements Load {
    private static final Random RANDOM = new Random();
    private static List<ServerNode> serverNodes = new ArrayList<>();
    private static List<String> middleServerList = new ArrayList<>();
    private static Integer weightSum = 0;


    @Override
    public String load(List<String> servers) {
        serverNodes.clear();
        middleServerList.clear();

        // TODO 权重可自定义实现
        for (String server : servers) {
            serverNodes.add(new ServerNode(server, getWeight(server)));// 默认为true
            serverNodes.add(new ServerNode(server, getWeight(server)));
            serverNodes.add(new ServerNode(server, getWeight(server)));
        }
        return getServer();
    }

    private Integer getWeight(String server) {
        return 1;
    }

    public static String getServer() {
        if (CollectionUtils.isEmpty(serverNodes)) {
            ArrayList<String> serverList = new ArrayList<>();
            Integer tempWeightSum = 0;
            for (ServerNode serverNode : serverNodes) {
                Integer weight = serverNode.getWeight();
                tempWeightSum += weight;
                for (int i = 0; i < weight; i++) {
                    serverList.add(serverNode.getServer());
                }
            }
            middleServerList = serverList;
            weightSum = tempWeightSum;
        }
        return middleServerList.get(RANDOM.nextInt(weightSum));
    }

}
